package com.leemon.mall.admin.security;

import com.leemon.mall.security.filter.LoginAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author limenglong
 * @create 2019-09-06 16:14
 * @desc 资源服务器配置
 **/
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private LoginAuthenticationFilter loginAuthenticationFilter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                //指定资源服务器的resourceId，配合cilents的resourceIds
                .resourceId("admin")
                //只能基于token认证
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

                //session创建策略
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                //匹配任意请求
                .requestMatchers().anyRequest()
                .and()
                //允许匿名用户
                .anonymous()
                .and()
                //请求授权
                .authorizeRequests()
                //以下请求允许直接访问资源
                .antMatchers("/webjars/**",
                        "/swagger/**",
                        "/v2/api-docs",
                        "/doc.html",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/captcha.jpg")
                .permitAll()
                //以下请求必须认证后才能访问资源
                .antMatchers("/**")
                .authenticated();
    }
}
